//
//  NewLeftMenuViewController.m
//  CenturyInterconnection
//
//  Created by mac on 16/8/4.
//  Copyright © 2016年 Shanghai DuRui Information Technology Company. All rights reserved.
//

#import "NewLeftMenuViewController.h"
#import "NewLeftVCModel.h"
#import "NewLeftCollectionViewCell.h"
#import "PromptCollectionViewCell.h"
#import "HomePageViewController.h"
#import "ProductListViewController.h"
#import "JPUSHService.h"

@interface NewLeftMenuViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *rightCollectionView;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray * scrDataArr;
@property (nonatomic ,strong) NSMutableArray *myData;
@property (nonatomic , strong) NSMutableArray * scrBtnArr;
@property (nonatomic ,assign) NSInteger selectedIndex;
@property (nonatomic,assign) NSInteger scrollTag;
@property (nonatomic, strong) UITableView *tableView;      
@property (nonatomic, assign) BOOL isRelate;
@property (nonatomic,retain) UIScrollView * scrollView;
@property (nonatomic,retain) UIView * myLineView;
@property (nonatomic,retain) UIButton * agoButton;

@property (nonatomic,retain) NSArray * childArray;
@end

@implementation NewLeftMenuViewController
//测试//111
- (void)viewDidLoad {
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];
    [JPUSHService setBadge:0];

    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.selectedIndex = 0;
    self.scrollTag = 1;
    
    self.title = @"Category";
    self.dataArr = [[NSMutableArray alloc]init];
    self.scrDataArr = [[NSMutableArray alloc]init];
    self.myData = [[NSMutableArray alloc]init];
    
    _childArray = [NSMutableArray arrayWithCapacity:0];
    
    _scrBtnArr = [[NSMutableArray alloc]init];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self getDatas:@"all"];
    
    [self createLineView];
    [self creatLeftNavBtn];
    [self TableView];
    [self ScrollView];
    [self CollectionView];
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"LeftMenuPage"];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"LeftMenuPage"];
}

-(void)createLineView
{
    
    _myLineView = [[UIView alloc]initWithFrame:CGRectMake((KScreenWidth*0.75)/3, KScreenHeight*0.05-2, (KScreenWidth*0.75)/3, 2)];
    _myLineView.backgroundColor = [UIColor blackColor];
    
}
//http://viprunningonline.com/api/index.php?main_page=category&cPath=120



-(void)getDatas:(NSString *)cpathString {
    
    // http://viprunningonline.com/api/index.php?main_page=category
    NSString*urlStrr=[NSString stringWithFormat:@"%@",HTTP_ADDRESS];
    NSDictionary*paramss=@{@"main_page":@"category",
                           @"cPath":cpathString};
    HttpManager*managerr=[[HttpManager alloc]init];
    if ([cpathString isEqualToString: @"all"])
    {
        [managerr getDataFromNetworkWithUrl:urlStrr parameters:paramss compliation:^(id data, NSError *error) {
            
            NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
            
            if ([number isEqualToString:@"1"]) {
                
                
                
                NSArray * dataArray = data[@"data"];
                for (NSDictionary * dict in dataArray)
                {
                    NSString * str = dict[@"categories_name"];
                    [_dataArr addObject:str];
                    
                    NSArray * arr = dict[@"child"];
                    NSMutableArray * smallArr = [[NSMutableArray alloc]init];
                    for (NSDictionary * dic in arr)
                    {
                        
                        [_scrDataArr addObject:dic[@"categories_name"]];
                        
                        NSArray * childArr = dic[@"child"];
                        NSMutableArray * minArr = [[NSMutableArray alloc]init];
                        for (NSDictionary * childDic in childArr) {
                            [minArr addObject:childDic];
                        }
                        [smallArr addObject:minArr];
                    }
                    
                    [_myData addObject:smallArr];
                }
                
                [self.scrBtnArr enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL * _Nonnull stop) {
                    [button setTitle:self.scrDataArr[idx] forState:UIControlStateNormal];
                }];
                
                [self.tableView reloadData];
                [self.rightCollectionView reloadData];
            }
            
            
        }];
        
        
    }
    
    
    
    
}

-(void)creatLeftNavBtn
{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:0];
    leftButton.frame=CGRectMake(0, 0, ACTUAL_WIDTH(23), ACTUAL_HEIGHT(23));
    [leftButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*item=[[UIBarButtonItem alloc]initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem=item;
}
-(void)comeBack
{
    [[SlideNavigationController sharedInstance]popViewControllerAnimated:YES];
}
//创建tableview左边栏
-(UITableView *)TableView{
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth*0.25,KScreenHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor grayColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = KScreenHeight*0.1;
        //        _tableView.scrollEnabled = NO;//不能滑动
        [self.view addSubview:_tableView];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    
    return _tableView;
}
//创建ScrollView
-(UIScrollView *)ScrollView
{
    
    if (_scrollView == nil)
    {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectZero];
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.contentSize = CGSizeMake(KScreenWidth*0.75, KScreenHeight*0.05);
        [self.view addSubview:_scrollView];
        [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(_tableView.mas_right);
            make.top.offset(64);
            make.width.mas_equalTo(self.view).multipliedBy(0.75);
            make.height.mas_equalTo(self.view).multipliedBy(0.05);
        }];
        
        for (NSInteger i = 0; i < 3; i ++)
        {
            
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(KScreenWidth*0.75/3*i, 0, KScreenWidth*0.75/3,  KScreenHeight*0.05);
            
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
            [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(scrollBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = i;
            [_scrBtnArr addObject:button];
            [_scrollView addSubview:button];
            if (i == 1)
            {
                button.selected = YES;
                _agoButton = button;
                [_scrollView addSubview:_myLineView];
            }
            else
            {
                button.selected = NO;
            }
            
        }
        
    }
    
    return _scrollView;
}
//创建右边视图
-(UICollectionView *)CollectionView
{
    //创建tableview的列表
    UICollectionViewFlowLayout *flowayout = [[UICollectionViewFlowLayout alloc]init];
    
    flowayout.itemSize = CGSizeMake((KScreenWidth*0.75-8)/3.0, (KScreenWidth*0.75-8)/3.0*1.3);//设置每个item的大小
    
    //设置上下左右的间距
    flowayout.sectionInset = UIEdgeInsetsMake(0, 2, 2, 2);
    //如果有多个区就可以拉动
    [flowayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    //横向最小间距
    flowayout.minimumInteritemSpacing = 1.5;
    flowayout.minimumLineSpacing = 1.5;
    
    
    UICollectionViewFlowLayout * promptFlow = [[UICollectionViewFlowLayout alloc]init];
    promptFlow.itemSize = CGSizeMake(KScreenWidth*0.75, KScreenHeight*0.95-70);
    
    if (_selectedIndex == 2 && _scrollTag == 0) {
        _rightCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:promptFlow];
        
        
    }
    else{
        _rightCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowayout];
        
        
    }
    [_rightCollectionView registerClass:[PromptCollectionViewCell class] forCellWithReuseIdentifier:@"PromptCollectionViewCell"];
    [_rightCollectionView registerClass:[NewLeftCollectionViewCell class] forCellWithReuseIdentifier:@"NewLeftCollectionViewCell"];
    
    
    _rightCollectionView.delegate = self;
    _rightCollectionView.dataSource = self;
    
    _rightCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_rightCollectionView];
    
    [_rightCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_tableView.mas_right);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.75);
        make.top.mas_equalTo(_scrollView.mas_bottom).mas_offset(0);
        make.bottom.mas_offset(0);
    }];
    
    return _rightCollectionView;
}

#pragma mark ---- scrollViewBtnMethod
-(void)scrollBtnClick:(UIButton *)button
{
    _scrollTag = button.tag;
    
    _agoButton.selected = NO;
    button.selected = YES;
    _agoButton = button;
    
    [UIView animateWithDuration:0.5 animations:^{
        _myLineView.frame = CGRectMake(button.tag*(KScreenWidth*0.75)/3, KScreenHeight*0.05-2, (KScreenWidth*0.75)/3, 2);
    }];
    
    [self.rightCollectionView reloadData];
    
    
}

#pragma mark ------- tableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return KScreenHeight*0.06;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.backgroundColor = [UIColor clearColor];
    if (KScreenWidth > 320) {
        cell.textLabel.font = [UIFont systemFontOfSize:12];
    }else
    {
        cell.textLabel.font = [UIFont systemFontOfSize:10];
    }
    
    cell.textLabel.textAlignment = NSTextAlignmentLeft;
    cell.textLabel.text = self.dataArr[indexPath.row];
    
    
    
    [_tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    
    return cell;
    
    
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    [_rightCollectionView scrollRectToVisible:CGRectMake(0, 0, self.rightCollectionView.frame.size.width, self.rightCollectionView.frame.size.height) animated:YES];
    
    _selectedIndex = indexPath.row;
    
    [_rightCollectionView reloadData];
    
}

#pragma mark------CollectionView的代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_myData.count != 0)
    {
        if(_selectedIndex == 2 )
        {
            if (_scrollTag == 0)
            {
                return 1;
            }
            else
                return [_myData[_selectedIndex][_scrollTag-1] count];
        }
        else{
            _childArray = _myData[_selectedIndex][_scrollTag];
            return self.childArray.count;
        }
    }
    else
        return self.childArray.count;
    
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NewLeftCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NewLeftCollectionViewCell" forIndexPath:indexPath];
    cell.collectionView_imageview.frame = CGRectMake(0, 0, (KScreenWidth*0.75-8)/3.0, (KScreenWidth*0.75-8)/3.0);
    cell.collectionView_Label.frame = CGRectMake(0, (KScreenWidth*0.75-8)/3.0, (KScreenWidth*0.75-8)/3.0, (KScreenWidth*0.75-8)/3.0*0.3);
    cell.collectionView_Label.numberOfLines = 0;
    cell.backgroundColor = [UIColor whiteColor];
    if (KScreenWidth > 320 && KScreenWidth < 400) {
        cell.collectionView_Label.font = [UIFont systemFontOfSize:11];
    }else if(KScreenWidth >= 400)
    {
        cell.collectionView_Label.font = [UIFont systemFontOfSize:12];
    }
    else
    {
        cell.collectionView_Label.font = [UIFont systemFontOfSize:9];
    }
    cell.collectionView_Label.textAlignment = NSTextAlignmentCenter;
    
    if (_selectedIndex == 2) {
        if (_scrollTag == 0) {
            PromptCollectionViewCell * pCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PromptCollectionViewCell" forIndexPath:indexPath];
            pCell.promptLabel.frame = CGRectMake(0, KScreenHeight*0.18, KScreenWidth*0.75-10, KScreenHeight*0.25);
            pCell.promptLabel.numberOfLines = 0;
            pCell.promptLabel.textAlignment = NSTextAlignmentCenter;
            if (KScreenWidth <= 320) {
                pCell.promptLabel.font = [UIFont systemFontOfSize:15];
            }
            else if(KScreenWidth < 400){
                pCell.promptLabel.font = [UIFont systemFontOfSize:17];
            }else{
                pCell.promptLabel.font = [UIFont systemFontOfSize:19];
            }
            
            pCell.promptLabel.text = @"The category is not a child of the goods, please look forward to!";
            pCell.promptLabel.textColor = [UIColor grayColor];
            return pCell;
        }
        else
        {
            NewLeftVCModel * model1 = [[NewLeftVCModel alloc]initWithCategoryDict:self.myData[_selectedIndex][_scrollTag-1][indexPath.item]];
            cell.collectionView_Label.text=model1.categories_name.uppercaseString;
            [cell.collectionView_imageview sd_setImageWithURL:[NSURL URLWithString:model1.categories_image] placeholderImage:nil];
        }
    }else{
        NewLeftVCModel *model=[[NewLeftVCModel alloc] initWithCategoryDict:self.myData[_selectedIndex][_scrollTag][indexPath.item]];
        cell.collectionView_Label.text=model.categories_name.uppercaseString;
        [cell.collectionView_imageview sd_setImageWithURL:[NSURL URLWithString:model.categories_image] placeholderImage:nil];
    }
    
    
    
    return cell;
}



//collertionview点击事件处理
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    NSLog(@"%ld行--%ld组-%ld行",(long)_selectedIndex,(long)_scrollTag,(long)indexPath.item);
    ProductListViewController * proListVC = [[ProductListViewController alloc] init];
    proListVC.ListOfSpeciesStr = @"products_list";
    if (_selectedIndex == 2) {
        proListVC.cPathStr = [_myData[_selectedIndex][_scrollTag-1][indexPath.row] valueForKey:@"id"] ;
        proListVC.categories_name = [_myData[_selectedIndex][_scrollTag-1][indexPath.row] valueForKey:@"categories_name"] ;
        NSDictionary *dict = @{@"index" : proListVC.categories_name };
        [MobClick event:@"LeftMenuPageClick" attributes:dict];
    }else
    {
        proListVC.cPathStr = [self.childArray[indexPath.row] valueForKey:@"id"] ;
        proListVC.categories_name = [self.childArray[indexPath.row] valueForKey:@"categories_name"] ;
        NSDictionary *dict = @{@"index" : proListVC.categories_name };
        [MobClick event:@"LeftMenuPageClick" attributes:dict];
    }
    
    
    [[SlideNavigationController sharedInstance] pushViewController:proListVC animated:YES];
    
}






#pragma mark ---- DisplayRightMenu
//- (BOOL)slideNavigationControllerShouldDisplayRightMenu
//{
//    return YES;
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
